package com.ruoyi.system.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.DictUtils;
import com.ruoyi.system.api.domain.ShCourse;
import com.ruoyi.system.api.domain.SysDictData;
import com.ruoyi.system.utils.ResourcesConfig;
import com.ruoyi.system.utils.TencentUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ShCourseMapper;
import com.ruoyi.system.service.IShCourseService;

import javax.imageio.ImageIO;

/**
 * 课程信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-07-18
 */
@Service
public class ShCourseServiceImpl implements IShCourseService 
{
    @Autowired
    private ShCourseMapper shCourseMapper;

    /**
     * 查询课程信息
     * 
     * @param id 课程信息主键
     * @return 课程信息
     */
    @Override
    public ShCourse selectShCourseById(Long id)
    {
        return shCourseMapper.selectShCourseById(id);
    }

    /**
     * 查询课程信息列表
     * 
     * @param shCourse 课程信息
     * @return 课程信息
     */
    @Override
    public List<ShCourse> selectShCourseList(ShCourse shCourse)
    {
        List<ShCourse> list = shCourseMapper.selectShCourseList(shCourse);
        List<SysDictData> dictLList = DictUtils.getDictCache("course_label");
        HashMap<String, String> dictLMap = new HashMap<>();
        for (SysDictData data:dictLList) {
            dictLMap.put(data.getDictValue(),data.getDictLabel());
        }
        for (ShCourse obj:list) {
            StringBuffer labelName = new StringBuffer();
            if (null != obj.getCourseLabel() && !"".equals(obj.getCourseLabel())) {
                String[] labelIdAry = obj.getCourseLabel().split(",");
                for (String labelId : labelIdAry) {
                    labelName.append(dictLMap.get(labelId)).append(",");
                }
            }
            obj.setLabelName(labelName.toString());
        }
        return list;
    }

    /**
     * 新增课程信息
     * 
     * @param shCourse 课程信息
     * @return 结果
     */
    @Override
    public int insertShCourse(ShCourse shCourse)
    {
        shCourse.setCreateTime(DateUtils.getNowDate());
        if (null!=shCourse.getVideoUrl()&&!"".equals(shCourse.getVideoUrl())) {
            try {
                TencentUtils tencentUtils = TencentUtils.getInstance();
                LocalDate date = LocalDate.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                String filePath = ResourcesConfig.getLocalFilePath()+"/"+formatter.format(date)+"/"+shCourse.getId()+".jpg";
                this.fetchFrame(shCourse.getVideoUrl(), filePath);
                File fileCover = new File(filePath);
                String urlCover = tencentUtils.uploadFile2Cos(TencentUtils.getMultipartFile(fileCover));
                shCourse.setVideoCover(urlCover);
                fileCover.delete();
            }catch (Exception e) {}
        }
        return shCourseMapper.insertShCourse(shCourse);
    }

    /**
     * 修改课程信息
     * 
     * @param shCourse 课程信息
     * @return 结果
     */
    @Override
    public int updateShCourse(ShCourse shCourse)
    {
        TencentUtils tencentUtils = TencentUtils.getInstance();
        if (null!=shCourse.getVideoUrl()&&!"".equals(shCourse.getVideoUrl())) {
            try {
                LocalDate date = LocalDate.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                String filePath = ResourcesConfig.getLocalFilePath()+"/"+formatter.format(date)+"/"+shCourse.getId()+".jpg";
                this.fetchFrame(shCourse.getVideoUrl(), filePath);
                File fileCover = new File(filePath);
                String urlCover = tencentUtils.uploadFile2Cos(TencentUtils.getMultipartFile(fileCover));
                shCourse.setVideoCover(urlCover);
                fileCover.delete();
            }catch (Exception e) {}
        }else {
            ShCourse item = shCourseMapper.selectShCourseById(shCourse.getId());
            if (null!=item.getVideoCover()&&!"".equals(item.getVideoCover())) {
                String[] keyAry = item.getVideoCover().split("aliyuncs.com/");
                tencentUtils.del(keyAry[1]);
            }
            if (null!=item.getVideoUrl()&&!"".equals(item.getVideoUrl())) {
                String[] keyAry = item.getVideoCover().split("aliyuncs.com/");
                tencentUtils.del(keyAry[1]);
            }
        }
        return shCourseMapper.updateShCourse(shCourse);
    }

    @Override
    public int updateShCoursePic(ShCourse shCourse) {
        return shCourseMapper.updateShCourse(shCourse);
    }

    public static void fetchFrame(String videoUrl, String imgUrl)throws Exception{
        FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(videoUrl);
        Java2DFrameConverter converter = new Java2DFrameConverter();
        frameGrabber.start();
        //解码长度
        int length = frameGrabber.getLengthInFrames();
        //时间
        int i = 0;
        Frame frame = null;
        while(i < length){
            //过滤前五帧，避免出现全黑的图片
            frame = frameGrabber.grabFrame();
            if(i > 10 && (frame.image != null)){
                break;
            }
            i ++;
        }
        // Frame frame = frameGrabber.grabFrame();
        BufferedImage bufferedImage = converter.convert(frame);
        //照片保存文件夹
        File targetFile = new File(imgUrl);
        //文件夹不存在就新建
        if(!targetFile.isDirectory()){
            targetFile.mkdirs();
        }
        //写入文件夹,以jpg图片格式
        ImageIO.write(bufferedImage, "jpg", targetFile);
        //停止转化为帧
        frameGrabber.stop();
    }

    /**
     * 批量删除课程信息
     * 
     * @param ids 需要删除的课程信息主键
     * @return 结果
     */
    @Override
    public int deleteShCourseByIds(Long[] ids)
    {
        TencentUtils tencentUtils = TencentUtils.getInstance();
        for (Long id:ids) {
            ShCourse item = shCourseMapper.selectShCourseById(id);
            if (null!=item.getVideoCover()&&!"".equals(item.getVideoCover())) {
                String[] keyAry = item.getVideoCover().split("aliyuncs.com/");
                tencentUtils.del(keyAry[1]);
            }
            if (null!=item.getVideoUrl()&&!"".equals(item.getVideoUrl())) {
                String[] keyAry = item.getVideoCover().split("aliyuncs.com/");
                tencentUtils.del(keyAry[1]);
            }
            shCourseMapper.deleteShCourseById(id);
        }
        return ids.length;
    }

    /**
     * 删除课程信息信息
     * 
     * @param id 课程信息主键
     * @return 结果
     */
    @Override
    public int deleteShCourseById(Long id)
    {
        return shCourseMapper.deleteShCourseById(id);
    }
}
